<!DOCTYPE html>
<html lang="zh">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>聊天助手</title>
        <!-- 引入 Bootstrap CSS -->
        <link
            rel="stylesheet"
            href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
        />
        <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
        <style>
            /* 添加新的基本样式 */
            body {
                font-family: Arial, sans-serif;
                margin: 0;
                padding: 0;
                background-color: #f4f4f4;
                display: flex;
                flex-direction: column;
                height: 98vh;
            }
            .chat-container {
                border: 1px solid #dedede;
                padding: 20px;
                background: rgb(47, 47, 47);
                flex: 1;
                overflow-y: auto;
                margin-bottom: 10px;
                display: flex;
                flex-direction: column;
            }
            .input-container {
                display: flex;
                margin-top: 10px;
                padding: 2px 8px;
            }
            .message {
                margin: 10px 0;
                max-width: 70%;
                display: flex;
                flex-direction: column;
            }
            .user-message {
                align-self: flex-end;
                color: rgb(223, 223, 223);
            }
            .bot-message {
                align-self: flex-start;
                color: rgb(223, 223, 223);
            }
            .message-box {
                padding: 12px 16px;
                font-size: 16px;
                border-radius: 12px;
                word-wrap: break-word;
            }
            .user-message .message-box {
                background-color: #0084ff;
                color: white;
                border-top-right-radius: 4px;
            }
            .bot-message .message-box {
                background-color: #3a3a3a;
                color: white;
                border-top-left-radius: 4px;
            }
            textarea {
                flex: 1;
                resize: none;
                border-radius: 20px;
                padding: 10px 15px;
            }
            button {
                margin-left: 10px;
                border-radius: 20px;
            }
        </style>
    </head>
    <body>
        <div class="chat-container" id="chat-container">
            <!-- 聊天记录将动态插入到这里 -->
        </div>
        <div class="input-container">
            <textarea
                id="input"
                class="form-control"
                placeholder="输入你的问题..."
                rows="1"
            ></textarea>
            <button id="submit-button" class="btn btn-primary">发送</button>
        </div>

        <script>
            const input = document.getElementById("input");
            const submitButton = document.getElementById("submit-button");
            const chatContainer = document.getElementById("chat-container");
            const chat_list = [];

            const url1 = "http://localhost:8002/ask";
            // const url1 = "http://localhost:11434/api/chat";

            input.value = "列出中国四大名著";

            // 1. 在输入框中回车
            input.addEventListener("keydown", (e) => {
                if (e.key === "Enter" && !e.ctrlKey) {
                    e.preventDefault(); // 阻止默认换行行为
                    submitButton.click(); // 触发提交按钮点击事件
                } else if (e.key === "Enter" && e.ctrlKey) {
                    // 按 Ctrl + Enter 时换行
                    const start = input.selectionStart;
                    const end = input.selectionEnd;
                    input.value =
                        input.value.substring(0, start) +
                        "\n" +
                        input.value.substring(end);
                    input.selectionStart = input.selectionEnd = start + 1;
                }
            });

            // 2. 提交按钮点击事件
            submitButton.addEventListener("click", async () => {
                require_ollama_api();
            });

            async function require_ollama_api() {
                const inputValue = input.value.trim();
                if (!inputValue) return; // 如果输入为空，则不处理

                // 添加用户消息
                const userMessage = document.createElement("div");
                userMessage.className = "message user-message";
                const textBox = document.createElement("div");
                textBox.className = "message-box";
                textBox.textContent = inputValue;
                userMessage.appendChild(textBox);
                chatContainer.appendChild(userMessage);

                chat_list.push({ role: "user", content: inputValue });

                // 清空输入框
                input.value = "";

                // 添加模型回复占位符
                const botMessage = document.createElement("div");
                botMessage.className = "message bot-message";
                const textBox2 = document.createElement("div");
                textBox2.className = "message-box";

                // 创建计时器显示
                let seconds = 0;
                const timer = setInterval(() => {
                    seconds++;
                    textBox2.innerHTML = `处理中 <span style="color: #888;">(${seconds}s)</span>`;
                }, 1000);

                botMessage.appendChild(textBox2);
                chatContainer.appendChild(botMessage);

                // 滚动到底部
                chatContainer.scrollTop = chatContainer.scrollHeight;

                try {
                    const response = await fetch(url1, {
                        method: "POST",
                        headers: {
                            "Content-Type": "application/json",
                        },
                        body: JSON.stringify({
                            model: "qwen2.5:7b",
                            messages: inputValue,
                            stream: true,
                        }),
                    });

                    const reader = response.body.getReader();
                    const decoder = new TextDecoder();
                    let result = "";
                    let count = 0;

                    // 一旦开始接收数据，清除计时器
                    clearInterval(timer);

                    while (true) {
                        const { done, value } = await reader.read();
                        if (done) break;

                        const chunk = decoder.decode(value);
                        const lines = chunk.split("\n");

                        for (const line of lines) {
                            console.log(line);
                            count += 1;
                            if (line.trim() === "") continue;
                            try {
                                const data = JSON.parse(line);
                                result += data.message.content;
                            } catch (error) {
                                result += line;
                            }

                            textBox2.innerHTML = `${marked.parse(result)}`;
                            await new Promise((resolve) =>
                                setTimeout(resolve, 20)
                            );
                        }

                        chatContainer.scrollTop = chatContainer.scrollHeight;
                    }
                    console.log("返回结果，行数count=" + count);
                    console.log("返回结果：" + result);
                    console.log(marked.parse(result));

                    chat_list.push({
                        role: "assistant",
                        content: result,
                    });
                } catch (error) {
                    // 发生错误时也要清除计时器
                    clearInterval(timer);
                    console.error("Error:", error);
                    botMessage.textContent = `调用 API 时出错: ${error.message}`;
                }
            }

            function getCurrentTime() {
                const now = new Date();
                const year = now.getFullYear();
                const month = String(now.getMonth() + 1).padStart(2, "0");
                const day = String(now.getDate()).padStart(2, "0");
                const hours = String(now.getHours()).padStart(2, "0");
                const minutes = String(now.getMinutes()).padStart(2, "0");
                const seconds = String(now.getSeconds()).padStart(2, "0");
                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            }
        </script>
    </body>
</html>
